package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.LogicException;
import com.heima.common.exception.ParamException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmLoginDto;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2023/3/5
 **/
@Service
public class WmUserServiceImpl implements WmUserService {

    @Resource
    private WmUserMapper wmUserMapper;

    @Override
    public Map<String, Object> login(WmLoginDto dto) {
        //1. 参数校验
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
           throw new ParamException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 根据用户名查询用户信息
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getUsername, dto.getName());
        WmUser wmUser = wmUserMapper.selectOne(wrapper);
        if (wmUser == null) {
            throw new LogicException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3. 根据上一步返回用户信息中的盐 结合 用户输入的密码 进行加盐加密 得到密文
        String encode = MD5Utils.encodeWithSalt(dto.getPassword(), wmUser.getSalt());
        //4. 使用上一步得到的密文 和 数据库中保存的密文进行比对
        //4.1 比对失败, 密码错误 , 返回错误信息
        if (!StringUtils.equals(encode, wmUser.getPassword())) {
            throw new LogicException(AppHttpCodeEnum.LOGIN_PARAM_ERROR);
        }
        //4.2 比对成功, 基于登录用户信息生成token
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        //5. 封装数据返回
        Map<String, Object> result = new HashMap<>(2);
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        result.put("user", wmUser);
        result.put("token", token);

        return result;
    }

    @Override
    public void save(WmUser wmUser) {
        if (wmUser == null) {
            throw new ParamException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (StringUtils.isEmpty(wmUser.getUsername()) || StringUtils.isEmpty(wmUser.getPassword()) || StringUtils.isEmpty(wmUser.getSalt())) {
            throw new ParamException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        wmUser.setStatus(1);
        wmUser.setCreatedTime(new Date());
        wmUser.setUpdatedTime(new Date());
        wmUser.setType(1);

        wmUserMapper.insert(wmUser);
    }
}
